Stream 流式编程
一、Stream介绍
1.什么是Stream
Stream 是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列
Stream和Collection集合的区别
- Collection是一种静态的内存数据结构,讲的是数据;主要面向内存,存储在内存中
- Stream是有关计算的,讲的是计算;面向CPU,通过CPU实现计算
2.Stream特点
- Stream自己不会存储元素
- Stream不会改变源对象。相反,他们会返回一个持有结果的新Stream
- Stream 操作是延迟执行的
- 这意味着他们会等到需要结果的时候才执行
- 即一旦执行终止操作,就执行中间操作链,并产生结果
- Stream一旦执行了终止操作,就不能再调用其它中间操作或终止操作了
3.Stream的操作三个步骤
- 创建 Stream
- 一个数据源(如:集合、数组),获取一个流
- 中间操作
- 每次处理都会返回一个持有结果的新Stream
- 即中间操作的方法返回值仍然是Stream类型的对象
- 因此中间操作可以是个操作链,可对数据源的数据进行n次处理
- 但是在终结操作前,并不会真正执行
- 终止操作(终端操作)
- 终止操作的方法返回值类型就不再是Stream了
- 因此一旦执行终止操作,就结束整个Stream操作了
- 一旦执行终止操作,就执行中间操作链,最终产生结果并结束Stream
二、创建Stream实例
1.通过集合创建Stream
Java8中的Collection接口被扩展,提供了两个获取流的方法:default Stream<E> stream(): 返回一个顺序流default Stream<E> parallelStream(): 返回一个并行流
java@Test public void test01(){ List<String> list = Arrays.asList("a", "b", "c", "d"); //创建顺序流(顺序执行) Stream<String> stream = list.stream(); //创建并行流(多线程并行执行,速度快) Stream<String> parallelStream = list.parallelStream(); }
2.通过数组创建Stream
Java8中的Arrays的静态方法stream()可以获取数组流:public static <T> Stream<T> stream(T[] array): 返回一个流public static IntStream stream(int[] array)public static LongStream stream(long[] array)public static DoubleStream stream(double[] array)
java@Test public void test02(){ String[] arr = {"hello","world"}; Stream<String> stream = Arrays.stream(arr); } @Test public void test03(){ int[] arr = {1,2,3,4,5}; IntStream stream = Arrays.stream(arr); }
3.通过Stream的of()创建Stream
可以调用
Stream类静态方法of(), 通过显示值创建一个流它可以接收任意数量的参数
public static<T> Stream<T> of(T… values): 返回一个流
java@Test public void test04(){ Stream<Integer> stream = Stream.of(1,2,3,4,5); stream.forEach(System.out::println); }
4.创建无限流
可以使用静态方法
Stream.iterate()和Stream.generate(), 创建无限流public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)public static<T> Stream<T> generate(Supplier<T> s)
java@Test public void test05() { // 迭代累加,获取前五个 Stream<Integer> stream = Stream.iterate(1, x -> x + 2); stream.limit(5).forEach(System.out::println); System.out.println("**********************************"); // 一直生成随机数,获取前五个 Stream<Double> stream1 = Stream.generate(Math::random); stream1.limit(5).forEach(System.out::println); }
三、Stream中间操作
多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理
而在终止操作时一次性全部处理,称为“惰性求值”
准备测试数据
// @Data 注在类上,提供类的get、set、equals、hashCode、toString等方法
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
// id
private int id;
// 名称
private String name;
// 年龄
private int age;
// 工资
private double salary;
}
public class EmployeeData {
public static List<Employee> getEmployees(){
List<Employee> list = new ArrayList<>();
list.add(new Employee(1001, "马化腾", 34, 6000.38));
list.add(new Employee(1002, "马云", 2, 19876.12));
list.add(new Employee(1003, "刘强东", 33, 3000.82));
list.add(new Employee(1004, "雷军", 26, 7657.37));
list.add(new Employee(1005, "李彦宏", 65, 5555.32));
list.add(new Employee(1006, "比尔盖茨", 42, 9500.43));
list.add(new Employee(1007, "任正非", 26, 4333.32));
list.add(new Employee(1008, "扎克伯格", 35, 2500.32));
return list;
}
}1.筛选(filter)
查询员工表中薪资大于7000的员工信息
java// 获取员工集合数据 List<Employee> employeeList = EmployeeData.getEmployees(); Stream<Employee> stream = employeeList.stream(); stream.filter(emp -> emp.getSalary() > 7000).forEach(System.out::println);
2.截断 (limit)
获取员工集合数据的前十个员工信息
javaemployeeList.stream().limit(10).forEach(System.out::println);
3.跳过(skip)
返回一个删除前五个员工信息的数据,与limit(n)互补
javaemployeeList.stream().skip(5).forEach(System.out::println);手动分页(current:当前页 size:每页条数)
javaList<Employee> employeeList = employeeList.stream() .skip((long) (current - 1) * size).limit(size) .collect(Collectors.toList());
4.去重(distinct)
通过流所生成元素的
hashCode()和equals()去除重复元素需要重写
hashCode和equals方法,否则不能去重javaemployeeList.add(new Employee(1009, "马斯克", 40, 12500.32)); employeeList.add(new Employee(1009, "马斯克", 40, 12500.32)); employeeList.add(new Employee(1009, "马斯克", 40, 12500.32)); employeeList.add(new Employee(1009, "马斯克", 40, 12500.32)); employeeList.stream().distinct().forEach(System.out::println);
5.映射(map/flatMap/mapToInt)
**map:**获取员工姓名长度大于3的员工的姓名
java//方式1:Lambda表达式 employeeList.stream().map(emp -> emp.getName()) .filter(name -> name.length() > 3).forEach(System.out::println); //方式2:方法引用第三种 类 :: 实例方法名 employeeList.stream().map(Employee::getName) .filter(name -> name.length() > 3).forEach(System.out::println);**flatMap:**当处理嵌套集合时,可以使用
flatMap将嵌套集合展平成一个新的StreamjavaList<List<Integer>> nestedList = Arrays.asList( Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6), Arrays.asList(7, 8, 9) ); nestedList.stream() .flatMap(item -> item.stream()) .forEach(System.out::println);**mapToInt:**将流中每个元素映射为
int类型java// 获取名字长度的总和 List<String> list1 = Arrays.asList("Apple", "Banana", "Orange", "Grapes"); IntStream intstream = list1.stream().mapToInt(String::length); int sum = intstream.sum();**mapToDouble:**将流中每个元素映射为
Double类型**mapToLong:**将流中每个元素映射为
Long类型
6.排序(sorted)
**sorted():**自然排序(从小到大),流中元素需实现
Comparable接口,否则报错java//sorted() 自然排序-升序 Integer[] arr = new Integer[]{345,3,64,3,46,7,3,34,65,68}; String[] arr1 = new String[]{"GG","DD","MM","SS","JJ"}; Arrays.stream(arr).sorted().forEach(System.out::println); Arrays.stream(arr1).sorted().forEach(System.out::println); //sorted() 自然排序-降序 Arrays.stream(arr).sorted(Comparator.reverseOrder()).forEach(System.out::println); Arrays.stream(arr1).sorted(Comparator.reverseOrder()).forEach(System.out::println); //因为Employee没有实现Comparable接口,所以报错! employeeList.stream().sorted().forEach(System.out::println);sorted(Comparator com):
Comparator排序器自定义排序java// 根据工资自然排序(从小到大) employeeList.stream().sorted(Comparator.comparing(Employee::getSalary)) .forEach(System.out::println); // 根据工资倒序(从大到小) employeeList.stream().sorted(Comparator.comparing(Employee::getSalary).reversed()) .forEach(System.out::println);
7.peek 和 forEach
相同点:
peek和forEach都是遍历流内对象并且对对象进行一定的操作不同点:
forEach返回void结束Stream操作,peek会继续返回Stream对象javemployeeList.stream() .map(Employee::getName) .peek(System.out::println) .filter(name -> name.length() > 3) .forEach(System.out::println);
四、Stream终止操作
- 终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:
List、Integer,甚至是void - 流进行了终止操作后,不能再次使用
1.匹配(allMatch/anyMatch/noneMatch)
**allMatch(Predicate p):**检查是否匹配所有元素
是否所有的员工的年龄都大于18
javaboolean allMatch = employeeList.stream().allMatch(emp -> emp.getAge() > 18);**anyMatch(Predicate p):**检查是否至少匹配一个元素
是否存在年龄大于18岁的员工
javaboolean anyMatch = employeeList.stream().anyMatch(emp -> emp.getAge() > 18);**noneMatch(Predicate p):**检查是否没有匹配所有元素
是不是没有年龄大于18岁的员工,没有返回
true,存在返回falsejavaboolean noneMatch = employeeList.stream().noneMatch(emp -> emp.getAge() > 18);
2.查找(findFirst/findAny)
**findFirst():**返回第一个元素
javaOptional<Employee> first = employeeList.stream().findFirst(); Employee employee = first.get();**findAny():**返回当前流中的任意元素
javaOptional<Employee> any = employeeList.stream().findAny(); Employee employee = any.get();ps:集合中数据为空,会抛异常No value present,后面会将Optional类的空值处理
3.聚合(max/min/count)
**max(Comparator c):**返回流中最大值,入参与排序
sorted的比较器一样,必须自然排序返回最高工资的员工
javaOptional<Employee> max = employeeList.stream().max(Comparator.comparingDouble(Employee::getSalary)); Employee employee = max.get();**min(Comparator c):**返回流中最小值,入参与排序
sorted的比较器一样,必须自然排序返回最低工资的员工
javaOptional<Employee> min = employeeList.stream().min(Comparator.comparingDouble(Employee::getSalary)); Employee employee = min.get();**count():**返回流中元素总数
返回所有工资大于7000的员工的个数
javalong count = employeeList.stream().filter(emp -> emp.getSalary() > 7000).count();
4.归约(reduce)
**reduce(BinaryOperator b):**可以将流中元素反复结合起来,得到一个值。返回
Optional<T>java// 计算1-10的自然数的和 List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Optional<Integer> reduce6 = list.stream().reduce(Integer::sum); Integer sum = reduce6.get(); // 计算公司所有员工工资的总和 Optional<Double> reduce7 = employeeList.stream().map(Employee::getSalary).reduce(Double::sum); Double aDouble = reduce7.get();**reduce(T identity, BinaryOperator b):**可以将流中元素反复结合起来,得到一个值。返回
T**T identity:**累加函数的初始值
不需要先获取
Optional再get(),直接可以获取结果,推荐使用java// 计算1-10的自然数的和 List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Integer reduce1 = list.stream().reduce(0, (x1, x2) -> x1 + x2); Integer reduce2 = list.stream().reduce(0, (x1, x2) -> Integer.sum(x1, x2)); Integer reduce3 = list.stream().reduce(0, Integer::sum); // 计算1-10的自然数的乘积 Integer reduce4 = list.stream().reduce(1, (x1, x2) -> x1 * x2); // 计算公司所有员工工资的总和 Double reduce5 = employeeList.stream().map(Employee::getSalary).reduce(0.0, Double::sum);
5.收集(collect)
**collect(Collector c):**将流转换为其他形式,接收一个
Collector接口的实现,用于给Stream中元素做汇总的方法Collector接口中方法的实现决定了如何对流执行收集的操作(如收集到List、Set、Map)Collectors实用类提供了很多静态方法,可以方便地创建常见收集器实例,如下
5.1.归集(toList/toSet/toMap)
**toList():**把流中元素收集到
List获取所有员工姓名集合
javaList<String> nameList1 = employeeList.stream().map(Employee::getName).collect(Collectors.toList()); // jdk16以后,collect(Collectors.toList())可以简写为.toList() List<String> nameList2 = employeeList.stream().map(Employee::getName).toList();**toSet():**把流中元素收集到
Set获取所有员工年龄
set集合,可以去重javaSet<Integer> ageList = employeeList.stream().map(Employee::getAge).collect(Collectors.toSet());**toMap():**把流中元素收集到
MapFunction.identity():
t -> t,相当于参数是什么,返回什么如下如果key重复,会抛异常java.lang.IllegalStateException: Duplicate key xxx
java// key-名称 value-员工对象 Map<String, Employee> employeeNameMap = employeeList.stream() .collect(Collectors.toMap(Employee::getName, Function.identity())); // key-名称 value-工资 Map<String, Double> nameSalaryMap = employeeList.stream() .collect(Collectors.toMap(Employee::getName, Employee::getSalary));toMap的第三个参数则是key重复后如何操作value的内容key重复可以只要旧的value数据,也可以新的value+旧的value等等java// key-名称 value-员工对象 Map<String, Employee> employeeNameMap = employeeList.stream() .collect(Collectors.toMap(Employee::getName, Function.identity(),(oldValue,newValue) -> oldValue)); // key-名称 value-工资 Map<String, Double> nameSalaryMap = employeeList.stream() .collect(Collectors.toMap(Employee::getName, Employee::getSalary,(oldValue,newValue) -> oldValue + newValue));
5.2.统计(counting/averaging/summing/maxBy/minBy)
**counting():**计算流中元素的个数
javaLong count = employeeList.stream().collect(Collectors.counting()); // 相当于 Long count2 = employeeList.stream().count();**averagingInt:**计算流中元素
Integer属性的平均值**averagingDouble:**计算流中元素
Double属性的平均值**averagingLong:**计算流中元素
Long属性的平均值返回值都是
DoublejavaDouble aDouble = employeeList.stream().collect(Collectors.averagingInt(Employee::getAge)); Double bDouble = employeeList.stream().collect(Collectors.averagingDouble(Employee::getSalary));**summingInt:**计算流中元素
Integer属性的总和**summingDouble:**计算流中元素
Double属性的总和**summingLong:**计算流中元素
Long属性的总和javaInteger count = employeeList.stream().collect(Collectors.summingInt(Employee::getAge)); Double total = employeeList.stream().collect(Collectors.summingDouble(Employee::getSalary));**maxBy():**计算流最大值
**minBy():**计算流最小值
java// 最大值 Optional<Employee> employee = employeeList.stream() .collect(Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary))); // 最小值 Optional<Employee> employee = employeeList.stream() .collect(Collectors.minBy(Comparator.comparingDouble(Employee::getSalary)));**summarizingInt():**汇总统计包括总条数、总和、平均数、最大值、最小值
javaIntSummaryStatistics summaryStatistics = employeeList.stream().collect(Collectors.summarizingInt(Employee::getAge)); System.out.println(summaryStatistics);// IntSummaryStatistics{count=8, sum=263, min=2, average=32.875000, max=65}
5.3.分组(partitioningBy/groupingBy)
**partitioningBy():**根据
true或false进行分区将员工按薪资是否高于6000分组
javaMap<Boolean, List<Employee>> listMap = employeeList.stream() .collect(Collectors.partitioningBy(emp -> emp.getSalary() > 6000));**groupingBy():**根据某属性值对流分组,属性为K,结果为V
将员工年龄分组
javaMap<Integer, List<Employee>> collect = employeeList.stream() .collect(Collectors.groupingBy(Employee::getAge));字符串集合获取每个字符串出现次数(用于查重)
javaList<String> strings = Arrays.asList("apple", "banana", "apple", "cherry", "banana", "date", "apple"); Map<String, Long> stringCountMap = strings.stream() .collect(Collectors.groupingBy(t -> t, Collectors.counting()));将员工年龄分组,并统计数量
javaMap<Integer, Long> collect = employeeList.stream() .collect(Collectors.groupingBy(Employee::getAge, Collectors.counting()));将员工按年龄分组,再汇总不同年龄的总金额
javaMap<Integer, Double> collect = employeeList.stream() .collect(Collectors.groupingBy(Employee::getAge, Collectors.summingDouble(Employee::getSalary)));将员工按年龄分组,获取工资集合
javaMap<Integer, List<Double>> integerListMap = employeeList.stream() .collect(Collectors.groupingBy(Employee::getAge, Collectors.mapping(Employee::getSalary, Collectors.toList())));先按员工年龄分组,再按工资分组
javaMap<Integer, Map<Double, List<Employee>>> collect = employeeList.stream() .collect(Collectors.groupingBy(Employee::getAge, Collectors.groupingBy(Employee::getSalary)));
5.4.接合(joining)
List<String> list = Arrays.asList("A", "B", "C");
String string = list.stream().collect(Collectors.joining("-"));
// 结果:A-B-C五、并行流parallelStream
1.并行流原理介绍
- 对于并行流,其在底层实现中,是沿用了Java7提供的fork/join分解合并框架进行实现
- fork根据cpu核数进行数据分块,join对各个fork进行合并
2.并行流和串行流对比
执行顺序
@Test
public void test1() {
List<Integer> list = Lists.newArrayList();
for (int i = 0; i < 5; i++) {
list.add(i);
}
System.out.println("*****************************************");
List<Integer> collect = list.stream().map(item -> {
System.out.println("串行数据:" + item + ",线程名称:" + Thread.currentThread().getName());
return item * 2;
}).collect(Collectors.toList());
System.out.println("*****************************************");
List<Integer> collect1 = list.parallelStream().map(item -> {
System.out.println("并行数据:" + item + ",线程名称:" + Thread.currentThread().getName());
return item * 2;
}).collect(Collectors.toList());
}输出结果:串行保证顺序,并行多线程不能保证顺序
*****************************************
串行数据:0,线程名称:main
串行数据:1,线程名称:main
串行数据:2,线程名称:main
串行数据:3,线程名称:main
串行数据:4,线程名称:main
*****************************************
并行数据:2,线程名称:main
并行数据:0,线程名称:ForkJoinPool.commonPool-worker-3
并行数据:3,线程名称:ForkJoinPool.commonPool-worker-3
并行数据:4,线程名称:ForkJoinPool.commonPool-worker-2
并行数据:1,线程名称:ForkJoinPool.commonPool-worker-1forEachOrdered保证执行顺序
@Test
public void test2() {
List<Integer> list = Lists.newArrayList();
for (int i = 0; i < 5; i++) {
list.add(i);
}
System.out.println("*****************************************");
list.stream().map(item -> {
return item + "|";
}).forEach(o -> {
System.out.println("forEach循环数据:" + o + ",线程名称:" + Thread.currentThread().getName());
});
System.out.println("*****************************************");
list.parallelStream().map(item -> {
return item + "|";
}).forEachOrdered(o -> {
System.out.println("forEachOrdered循环数据:" + o + ",线程名称:" + Thread.currentThread().getName());
});
}输出结果:并行流forEachOrdered可以保证执行顺序
*****************************************
forEach循环数据:0|,线程名称:main
forEach循环数据:1|,线程名称:main
forEach循环数据:2|,线程名称:main
forEach循环数据:3|,线程名称:main
forEach循环数据:4|,线程名称:main
*****************************************
forEachOrdered循环数据:0|,线程名称:ForkJoinPool.commonPool-worker-3
forEachOrdered循环数据:1|,线程名称:ForkJoinPool.commonPool-worker-1
forEachOrdered循环数据:2|,线程名称:ForkJoinPool.commonPool-worker-1
forEachOrdered循环数据:3|,线程名称:ForkJoinPool.commonPool-worker-1
forEachOrdered循环数据:4|,线程名称:ForkJoinPool.commonPool-worker-1执行效率
@Test
public void test3() {
List<Integer> list = Lists.newArrayList();
for (int i = 0; i < 1000000; i++) {
list.add(i);
}
long l1 = System.currentTimeMillis();
List<Integer> collect = list.stream().map(item -> {
return item * 2;
}).collect(Collectors.toList());
System.out.println("串行流耗时:" + (System.currentTimeMillis() - l1) + "ms");
long l2 = System.currentTimeMillis();
List<Integer> collect1 = list.parallelStream().map(item -> {
return item * 2;
}).collect(Collectors.toList());
System.out.println("并行流流耗时:" + (System.currentTimeMillis() - l2) + "ms");
}输出结果:并行流明显高于串行
串行流耗时:17ms
并行流流耗时:81ms六、Optional 类
Optional类内部结构(value为实际存储的值)
public final class Optional<T> {
// 空Optional对象,value为null
private static final Optional<?> EMPTY = new Optional<>();
// 实际存储的内容
private final T value;
// 私有的构造
private Optional() {
this.value = null;
}
...
}1.构建Optional对象
@Test
public void optionalTest(){
Integer value1 = null;
Integer value2 = 10;
// 允许传递为null参数
Optional<Integer> a = Optional.ofNullable(value1);
// 如果传递的参数是null,抛出异常NullPointerException
Optional<Integer> b = Optional.of(value2);
// 空对象,value为null
Optional<Object> c = Optional.empty();
}2.获取value值,空值的处理
@Test
public void optionalTest() {
Integer value1 = null;
Optional<Integer> a = Optional.ofNullable(value1);
System.out.println("value值是否为null:" + a.isPresent());
System.out.println("获取value值,空报错空指针:" + a.get());
System.out.println("获取value值,空返回默认值0:" + a.orElse(0));
System.out.println("获取value值,空返回Supplier返回值:" + a.orElseGet(() -> 100));
System.out.println("获取value值,空抛出异常:" + a.orElseThrow(() -> new RuntimeException("value为空")));
}3.处理value值,空值不处理不报错
ifPresent方法内会判断不为空才操作
java@Test public void optionalTest() { Integer value1 = 10; Optional<Integer> a = Optional.ofNullable(value1); // 空不处理,非空则根据Consumer消费接口处理 a.ifPresent(o -> System.out.println("ifPresent value值:" + o)); // 10 // 空不处理,filter过滤 a.filter(o -> o > 1).ifPresent(o -> System.out.println("filter value值:" + o)); // 10 // 空不处理,map映射 a.map(o -> o + 10).ifPresent(o -> System.out.println("map value值:" + o)); // 20 // 空不处理,flatMap映射 a.flatMap(o -> Optional.of(o + 20)).ifPresent(o -> System.out.println("flatMap value值:" + o)); // 30 }